/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 TCPConnector.cpp. Created on: 20.08.2009 15:37:40
 */

#include "smartobjects/network/tcp/TCPConnector.hpp"

namespace smartobjects {

TCPConnector::TCPConnector(TCPSharedResources::SharedPtr poSharedResources):
	TCPConnection(poSharedResources) {

}

TCPConnector::~TCPConnector() {
	close();
}

void TCPConnector::prepareToConnect(void) throw (const IOException&)  {
	if(!m_poSocketURI)
		throw IOException("Destination URI to connect isn't specified");

	if ( this->isOpen() ) {
		this->close();
	}

	m_hSocket = smartobjects::sockets::osimpl::createSocket(SOCK_STREAM,IPPROTO_TCP);
	if ( m_hSocket == -1 ) {
		throw IOException("Unable to create a socket to connect: " + getLastOSErrorString());
	}

	m_bStoppedState = false;
}

void TCPConnector::connect(void) throw (const IOException&)  {
	boost::recursive_mutex::scoped_lock oLock(m_mxSocketLock);
	prepareToConnect();
	int nConnectResult = smartobjects::sockets::osimpl::connectSocket ( m_hSocket, this->m_poSocketURI->getSocketAddr() );

	if (!smartobjects::sockets::osimpl::isSuccessConnectResult(nConnectResult)) {
		close();
		throw IOException( "Unable to connect to a remote host at "+this->m_poSocketURI->getURIStr()+": "+ getLastOSErrorString());
	}

	// Start processing (reading from the socket)
	start();
}

void TCPConnector::connectAsync(void) throw (const IOException&)  {
	boost::recursive_mutex::scoped_lock oLock(m_mxSocketLock);

	prepareToConnect();
	smartobjects::sockets::osimpl::setNoneBlockMode ( m_hSocket, true );
	int nConnectResult = smartobjects::sockets::osimpl::connectSocket ( m_hSocket, this->m_poSocketURI->getSocketAddr() );
	if (!smartobjects::sockets::osimpl::isSuccessConnectResult(nConnectResult)) {
		close();
		throw IOException( "Unable to start connecting to a remote host at "+this->m_poSocketURI->getURIStr()+": "+ getLastOSErrorString());
	}

	m_poMultiplexer->addSocketConnector ( m_hSocket,
		boost::bind ( &TCPConnector::onConnect, this, _1 )
	);
}

void TCPConnector::close(void) {
	boost::recursive_mutex::scoped_lock oAsyncEventLock ( m_mxAsyncEvent );
	m_bStoppedState = true;
	oAsyncEventLock.unlock();
	boost::recursive_mutex::scoped_lock oLock(m_mxSocketLock);
	if(isOpen()) {
		m_poMultiplexer->removeSocketConnector ( m_hSocket );
	}
	TCPConnection::close();
}

void TCPConnector::onConnect(bool bStatus) throw() {
	boost::recursive_mutex::scoped_lock oAsyncEventLock ( m_mxAsyncEvent );
	if (m_bStoppedState)
		return;
	SafeForReleaseMethodLock oReleaseLock(this);
	if(bStatus) {
		// boost::recursive_mutex::scoped_lock oLock(m_mxSocketLock);
		bool bIsFiredConnect = false;
		try {
			if(m_poHandshakeManager==NULL) {
				fireOnConnected();
				bIsFiredConnect = true;
			}
			else {
				m_poHandshakeManager->beginHandshake();
			}

			start();
		}
		catch(const std::exception& ex) {
			if(bIsFiredConnect)
				fireOnDisconnected();
			else
				fireOnConnectionFailure( ex.what() );
		}
	}
	else {
		fireOnConnectionFailure( getLastOSErrorString() );
	}
}


void TCPConnector::setEndpointURI(URI* poURI) throw (const IOException&)  {
	const std::string& sURI = poURI->getURIStr();
	smartobjects::sockets::SocketURI* poSocketURI = new smartobjects::sockets::SocketURI( sURI );
	TCPConnection::setEndpointURI (
		poSocketURI
	);
	poSocketURI->release();
}

void TCPConnector::fireOnConnected() {
	if(isHandshaked()) {
		boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
		m_oPALConnectionListeners.activate();
		foreach(IConnectionListener* poListener, m_aConnectionListeners) {
			poListener->onConnected(this);
		}
		processingPostActionConnectionListeners();
	}
}

void TCPConnector::fireOnConnectionFailure(const std::string& sErrorMessage) {
	if(isHandshaked()) {
		boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
		m_oPALConnectionListeners.activate();
		foreach(IConnectionListener* poListener, m_aConnectionListeners) {
			poListener->onConnectionFailure(this, sErrorMessage);
		}
		processingPostActionConnectionListeners();
	}
}

bool TCPConnector::isAcceptorConnection() {
	return false;
}

}
